unit HandlePipeThread;

interface

uses
  Windows, Classes, SysUtils, SyncObjs;

type
  THandlePipeThread = class (TThread)
  private
    FList : TList;
  protected
    FCS : TCriticalSection;
  public
    WaitForTerminateEvent : THandle;
    
    constructor Create(CreateSuspended: Boolean); virtual;
    destructor Destroy; override;

    procedure Clear;
    procedure Add(Data: TObject);
    function Get(Data:TObject):boolean;

    property Terminated; 
  end;

implementation

{ TRyuSocketClientThread }

procedure THandlePipeThread.Add(Data: TObject);
begin
  FCS.Enter;
  try
    FList.Add(Data);
  finally
    FCS.Leave;
  end;
end;

procedure THandlePipeThread.Clear;
var
  Loop : Integer;
  Data: TObject;
begin
  FCS.Enter;
  try
    for Loop := 0 to FList.Count - 1 do Begin
      Data := FList.Items[Loop];
      Data.Free;
    End;

    FList.Clear;
  finally
    FCS.Leave;
  end;
end;

constructor THandlePipeThread.Create(CreateSuspended: Boolean);
begin
  FreeOnTerminate := false;

  FList := TList.Create;
  FCS := TCriticalSection.Create;
  WaitForTerminateEvent := CreateEvent(nil, false, false, '');

  inherited Create(CreateSuspended);
end;

destructor THandlePipeThread.Destroy;
begin
  Clear;

  FCS.Free;
  FList.Free;
  CloseHandle(WaitForTerminateEvent);

  inherited;
end;

function THandlePipeThread.Get(Data: TObject): Boolean;
begin
  FCS.Enter;
  try
    Result := false;

    if FList.Count = 0 then Exit;

    Result := true;
    Data:= TObject(FList[0]);
    FList.Delete(0);
  finally
    FCS.Leave;
  end;
end;

end.

